package com.sc.nft.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.GasConsumeDTO;
import com.sc.nft.entity.vo.AddCdkActivityVO;
import com.sc.nft.entity.vo.CdkExchangeRecordVO;
import com.sc.nft.entity.vo.CdkGasCostVO;
import com.sc.nft.entity.vo.PageCdkVO;
import com.sc.nft.entity.vo.ProductCdkRecordVO;
import com.sc.nft.entity.vo.ecology.EcologyCastGasVO;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.*;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.util.ShareCodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@Service
public class CDKProductServiceImpl implements CDKProductService {

    private final ProductCdkDao productCdkDao;
    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;
    private final ProductStockService productStockService;
    private final BoxItemService boxItemService;
    private final BoxProductDao boxProductDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final UserCollectionService userCollectionService;
    private final ProductCdkRecordDao productCdkRecordDao;
    private final CdkActivityInfoDao cdkActivityInfoDao;
    private final EquityPropsDao equityPropsDao;
    private final UserEquityPropsService userEquityPropsService;
    private final UserRelevanceDao userRelevanceDao;
    private final UserConsensusService userConsensusService;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final OrderGasService orderGasService;
    private final UserWalletDao userWalletDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exchangeCdk(String cdk, UserInfo user) throws GlobalException {

        ProductCdk oneByCdk = productCdkDao.getOneByCdk(cdk);

        if (ObjectUtil.isEmpty(oneByCdk)) {
            throw new GlobalRunTimeException(ErrorCode.CDK_IS_DOES_NOT_EXIST);
        }


        CdkActivityInfo byId = cdkActivityInfoDao.getById(oneByCdk.getCdkActivityId());
        Assert.notNull(byId, () -> new GlobalRunTimeException(ErrorCode.CDK_ACTIVITY_IS_DOES_NOT_EXIST));
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(byId.getDaoId());
        Assert.notNull(userCreatorInfo, () -> new GlobalRunTimeException("DAO不存在"));

        if (userCreatorInfo.getUserId().longValue() != user.getId().longValue()) {
            Assert.isTrue(userRelevanceDao.shaolinTempleContractDisputes(userCreatorInfo.getUserId(), user.getId()), () -> new GlobalRunTimeException("暂未获取资格"));
        }


        DateTime now = DateTime.now();
        if (now.isBefore(oneByCdk.getBeginTime())) {
            throw new GlobalRunTimeException(ErrorCode.REDEMPTION_CODE_HAS_NOT_STARTED_YET);
        }

        if (now.isAfter(oneByCdk.getEndTime())) {//过期
            throw new GlobalRunTimeException(ErrorCode.REDEMPTION_CODE_HAS_EXPIRED);
        }

        if (oneByCdk.getIsUse() && byId.getRedemptionCodeRule().getCode() == RedemptionCodeRuleEnum.RANDOM.getCode()) {
            throw new GlobalRunTimeException(ErrorCode.REDEMPTION_CODE_USER);
        }

        ProductCdkRecord productCdkRecord = new ProductCdkRecord();
        ProductCdkTypeEnum productType = oneByCdk.getProductType();
        //自定义规则兑换码
        if (RedemptionCodeRuleEnum.CUSTOM.getCode() == byId.getRedemptionCodeRule().getCode()) {

//            ArrayList<Long> collectionIds = new ArrayList<>();
//            collectionIds.add(117L);

            //判断用户是否持有官方身份卡
//            List<UserCollection> collectionIdByUserCreatorId = userCollectionService.getCollectionIdByUserId(user.getId(),collectionIds);

            //如果持有任意身份卡不允许兑换
//            Assert.isFalse(ObjectUtil.isNotEmpty(collectionIdByUserCreatorId),()->new GlobalRunTimeException("不满足兑换条件"));

            //库存
            Assert.isFalse(ObjectUtil.isNull(byId.getRemainingQuantity()) || byId.getRemainingQuantity() < 1, () -> new GlobalRunTimeException("活动已过期"));

            //获取配置使用上限
            Integer userUseLimit = byId.getUserUseLimit();

            //获取用户已经使用了几次
            Integer userUsedLimit = productCdkRecordDao.getListByUserIdAndActivityId(user.getId(), byId.getId());
            Assert.isFalse(userUseLimit <= userUsedLimit, () -> new GlobalRunTimeException("该兑换码已达到个人兑换上限"));

            //判断兑换码类型是否正确 自定义兑换码只能兑换权益道具
            Assert.isTrue(ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT.getCode() == byId.getProductType().getCode(), () -> new GlobalRunTimeException("兑换码无效"));

            //给用户兑换权益道具
            EquityProps equityProps = equityPropsDao.getById(oneByCdk.getProductId());
            UserEquityProps userEquityProps = userEquityPropsService.addEquityPropsByUser(equityProps, user.getId(), UserEquityPropsGetTypeEnum.CDK, 1, byId.getFirstTitle(), byId.getId(), BigDecimal.ZERO, UserEquityPropsGetTypeEnum.CDK, byId.getId());

            //添加记录
            productCdkRecord.setFirstTitle(equityProps.getFirstTitle());
            productCdkRecord.setCreationContent(equityProps.getCreationContent());
            productCdkRecord.setUserId(user.getId());
            productCdkRecord.setProductId(equityProps.getId());
            productCdkRecord.setProductType(ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT);
            productCdkRecord.setCdk(cdk);
            productCdkRecord.setUserCollectionId(userEquityProps.getId());
            productCdkRecord.setCdkActivityId(oneByCdk.getCdkActivityId());
            productCdkRecord.insert();
            //调整兑换码库存 剩余库存+ 1

            cdkActivityInfoDao.subStock(byId.getId());
        } else {
            if (productType == ProductCdkTypeEnum.NFT_PRODUCT) {
                DigitalCollectionProductInfo productInfo = digitalCollectionProductInfoDao.getById(oneByCdk.getProductId());
                //region 校验用户注册时间
                if (Objects.nonNull(productInfo.getIsRegisterTime())
                        && productInfo.getIsRegisterTime()) {
                    if (user.getCreateTime().before(productInfo.getRegisterBeginTime())
                            || user.getCreateTime().after(productInfo.getRegisterEndTime())) {
                        throw new GlobalException("当前注册时间不满足条件");
                    }
                }
                //endregion
                List<ProductCdkRecord> list = productCdkRecordDao.getListByUserIdAndProductId(user.getId(), productInfo.getId());
                if (list.size() >= productInfo.getUpperLimit()) {
                    throw new GlobalRunTimeException(ErrorCode.THS_NUMBER_OR_REDMPTIONS_HAS_BEEN_CAPPED);
                }
                //添加到个人藏品表
                cdkGrant(user.getId(), productInfo, cdk, oneByCdk.getCdkActivityId());
            } else if (productType == ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT) {
                EquityProps equityProps = equityPropsDao.getById(oneByCdk.getProductId());


                UserEquityProps userEquityProps = userEquityPropsService.addEquityPropsByUser(equityProps, user.getId(), UserEquityPropsGetTypeEnum.CDK, 1, byId.getFirstTitle(), byId.getId(), BigDecimal.ZERO, UserEquityPropsGetTypeEnum.CDK, byId.getId());
                productCdkRecord.setFirstTitle(equityProps.getFirstTitle());
                productCdkRecord.setCreationContent(equityProps.getCreationContent());
                productCdkRecord.setUserId(user.getId());
                productCdkRecord.setProductId(equityProps.getId());
                productCdkRecord.setProductType(ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT);
                productCdkRecord.setCdk(cdk);
                //productCdkRecord.setCollectionUuid(userEquityProps.getUserProductUuid());
                productCdkRecord.setUserCollectionId(userEquityProps.getId());
                productCdkRecord.setCdkActivityId(oneByCdk.getCdkActivityId());
                productCdkRecord.insert();
            }
        }

        if (byId.getGasConf()) {
            //CDK兑换上链费
            GasConsumeDTO gasConsume = getGasConsumeDTO(user, byId);
            orderGasService.gasConsume(gasConsume);
        }
        oneByCdk.setIsUse(Boolean.TRUE);
        oneByCdk.updateById();
    }
    
    @Override
    public CdkGasCostVO getGasCost(String cdk, Long userId) {
        ProductCdk oneByCdk = productCdkDao.getOneByCdk(cdk);
        
        if (ObjectUtil.isEmpty(oneByCdk)) {
            throw new GlobalRunTimeException(ErrorCode.CDK_IS_DOES_NOT_EXIST);
        }
        
        CdkActivityInfo cdkActivityInfo = cdkActivityInfoDao.getById(oneByCdk.getCdkActivityId());
        Assert.notNull(cdkActivityInfo, () -> new GlobalRunTimeException(ErrorCode.CDK_ACTIVITY_IS_DOES_NOT_EXIST));
        CdkGasCostVO cdkGasCostVO=new CdkGasCostVO();
        EcologyCastGasVO ecologyCastGasVO=new EcologyCastGasVO();
        ecologyCastGasVO.setGasConf(cdkActivityInfo.getGasConf());
        ecologyCastGasVO.setConsumeCost(cdkActivityInfo.getConsumeCost());
        ecologyCastGasVO.setConsumeType(cdkActivityInfo.getConsumeType());
        UserWallet userWallet = userWalletDao.getByUserId(userId);
        ecologyCastGasVO.setBalance(Objects.isNull(userWallet)?BigDecimal.ZERO:userWallet.getBalance());
        cdkGasCostVO.setEcologyCastGas(ecologyCastGasVO);
        return cdkGasCostVO;
    }
    
    private  GasConsumeDTO getGasConsumeDTO(UserInfo user, CdkActivityInfo byId) {
        GasConsumeDTO gasConsume=new GasConsumeDTO();
        gasConsume.setConsumeCost(byId.getConsumeCost());
        gasConsume.setUserId(user.getId());
        gasConsume.setGasConsumeType(GasConsumeTypeEnum.BALANCE);
        gasConsume.setWalletDetailType(WalletDetailTypeEnum.CDK_EXCHANGE);
        gasConsume.setProductId(byId.getProductId());
        gasConsume.setCollectionId(0L);
        gasConsume.setOrderGasType(OrderGasTypeEnum.CDK_EXCHANGE);
        return gasConsume;
    }
    
    @Override
    public Page<ProductCdkRecordVO> getExchangeList(Integer pageNo, Integer pageSize) {
        UserInfo user = UserPool.getUser();
        return productCdkRecordDao.getUserExchangeListByPage(user.getId(), new Page(pageNo, pageSize));
    }

    @Override
    public Page<AddCdkActivityVO> getCdkActivityList(Integer pageNo, Integer pageSize, String name) {
        Page<AddCdkActivityVO> cdkActivityList = cdkActivityInfoDao.getCdkActivityList(new Page<>(pageNo, pageSize), name);
        for (AddCdkActivityVO record : cdkActivityList.getRecords()) {
            EcologyCastGasVO ecologyCastGas = new EcologyCastGasVO();
            ecologyCastGas.setGasConf(record.getGasConf());
            ecologyCastGas.setConsumeCost(record.getConsumeCost());
            ecologyCastGas.setConsumeType(record.getConsumeType());
            record.setEcologyCastGas(ecologyCastGas);
        }
        return cdkActivityList;
    }

    @Override
    public Page<PageCdkVO> getPageCdk(Long cdkActivityId, String cdk, Integer isUse, Integer isExpired, Integer pageNo, Integer pageSize) {
        //根据不同的生成规则
        CdkActivityInfo cdkActivityInfo = cdkActivityInfoDao.getById(cdkActivityId);
        Assert.isFalse(ObjectUtil.isNull(cdkActivityInfo), () -> new GlobalRunTimeException("兑换码活动不存在"));
        if (RedemptionCodeRuleEnum.RANDOM.getCode() == cdkActivityInfo.getRedemptionCodeRule().getCode()) {

            return productCdkDao.getPageCdk(new Page<>(pageNo, pageSize), cdkActivityId, cdk, isUse, isExpired);
        } else {
            //只需要获取一条
            pageSize = 1;
            return productCdkDao.getPageCustomCdk(cdkActivityId, pageNo, pageSize);
        }
    }

    @Override
    public void updateCdkActivity(Long id,
                                  String activityTitle,
                                  String activityDescription,
                                  String beginTime,
                                  String endTime,
                                  ProductCdkTypeEnum productType,
                                  String firstTitle,
                                  Long productId,
                                  Boolean gasConf,
                                  GasConsumeTypeEnum consumeType,
                                  BigDecimal consumeCost,
                                  Long daoId, RedemptionCodeRuleEnum type, Integer redemptionTotal, Integer userUseLimit) {
        CdkActivityInfo cdkActivityInfo = cdkActivityInfoDao.getById(id);
        if (ObjectUtil.isEmpty(cdkActivityInfo)) {
            throw new GlobalRunTimeException(ErrorCode.CDK_ACTIVITY_IS_DOES_NOT_EXIST);
        }

        //如果是自定义CDK 不允许修改兑换码总量和用户使用上限
        if (RedemptionCodeRuleEnum.CUSTOM.getCode() == type.getCode()) {
            Assert.isTrue(cdkActivityInfo.getRedemptionTotal().equals(redemptionTotal), () -> new GlobalRunTimeException("兑换码生成总量不允许修改"));
            Assert.isTrue(cdkActivityInfo.getUserUseLimit().equals(userUseLimit), () -> new GlobalRunTimeException("用户使用上限不允许修改"));
        }

        cdkActivityInfo.setDaoId(daoId);

        if (productType == ProductCdkTypeEnum.NFT_PRODUCT) {
            DigitalCollectionProductInfo productInfo = digitalCollectionProductInfoDao.getById(productId);
            if (ObjectUtil.isEmpty(productInfo)) {
                throw new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND);
            }
        } else if (productType == ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT) {
            EquityProps equityProps = equityPropsDao.getById(productId);
            if (ObjectUtil.isEmpty(equityProps)) {
                throw new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_DO_NOT_EXIST);
            }
        }

        Integer count = productCdkDao.getCountByCdkActivityId(cdkActivityInfo.getId());
        if (count == 0) {
            cdkActivityInfo.setBeginTime(DateUtil.parse(beginTime, "yyyy-MM-dd HH:mm:ss"));
            cdkActivityInfo.setEndTime(DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"));
            cdkActivityInfo.setProductType(productType);
            cdkActivityInfo.setFirstTitle(firstTitle);
            cdkActivityInfo.setProductId(productId);
        }
        cdkActivityInfo.setGasConf(gasConf);
        if (gasConf) {
            cdkActivityInfo.setConsumeCost(consumeCost);
            cdkActivityInfo.setConsumeType(consumeType);
        }
        cdkActivityInfo.setActivityTitle(activityTitle);
        cdkActivityInfo.setActivityDescription(activityDescription);
        cdkActivityInfo.setRedemptionTotal(redemptionTotal);
        cdkActivityInfo.updateById();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateCDK(Long activityId, Integer generateNum) {
        CdkActivityInfo cdkActivityInfo = cdkActivityInfoDao.getById(activityId);
        if (ObjectUtil.isEmpty(cdkActivityInfo)) {
            throw new GlobalRunTimeException(ErrorCode.CDK_ACTIVITY_IS_DOES_NOT_EXIST);
        }

        DateTime now = DateTime.now();
        if (now.isAfter(cdkActivityInfo.getEndTime())) {
            throw new GlobalRunTimeException(ErrorCode.WRONG_TIME_SETTING);
        }


        ProductCdkTypeEnum productType = cdkActivityInfo.getProductType();
        if (productType == ProductCdkTypeEnum.NFT_PRODUCT) {//NFT商品 校验库存
            DigitalCollectionProductInfo nftProduct = digitalCollectionProductInfoDao.getById(cdkActivityInfo.getProductId());
            if (!nftProduct.getStatus()) {
                throw new GlobalRunTimeException(ErrorCode.PRODUCT_HAS_BEEN_DESCONTINUED);
            }

            if (nftProduct.getIsSoldOut()) {
                throw new GlobalRunTimeException(ErrorCode.COLLECTION_IS_SOLD_OUT);
            }
            if (ObjectUtil.isNull(nftProduct)) {
                throw new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND);
            }
            ProductStock productStock = productStockService.getProductStock(nftProduct.getId(), null, null);
            if (ObjectUtil.isEmpty(productStock)) {
                throw new GlobalRunTimeException(ErrorCode.PRODUCT_HAS_BEEN_DESCONTINUED);
            }
            if (productStock.getUsableCount() <= 0) {
                throw new GlobalRunTimeException(ErrorCode.COUNT_NOT_ENOUGH);
            }

            if (productStock.getUsableCount() < generateNum) {
                throw new GlobalRunTimeException(ErrorCode.COUNT_NOT_ENOUGH);
            }
            productStockService.deductStock(nftProduct.getId(), nftProduct.getRelationId(), generateNum, 0l, CommodityType.CDK_PRODUCT);

        } else if (productType == ProductCdkTypeEnum.EQUITY_PROPS_PRODUCT) {//权益道具商品 校验库存
            EquityProps equityProps = equityPropsDao.getById(cdkActivityInfo.getProductId());
            if (ObjectUtil.isEmpty(equityProps)) {
                throw new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_DO_NOT_EXIST);
            }
            if (!equityProps.getStatus()) {
                throw new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_HAS_BEEN_DESCONTINUED);
            }
        }


        HashSet<String> cdks = ShareCodeUtil.genCDK(generateNum, 16);
        List<ProductCdk> productCdkList = Lists.newArrayList();
        for (String cdk : cdks) {
            ProductCdk productCdk = new ProductCdk();
            productCdk.setCdk(cdk);
            productCdk.setCdkActivityId(activityId);
            productCdk.setProductId(cdkActivityInfo.getProductId());
            productCdk.setProductType(cdkActivityInfo.getProductType());
            productCdk.setBeginTime(cdkActivityInfo.getBeginTime());
            productCdk.setEndTime(cdkActivityInfo.getEndTime());
            productCdkList.add(productCdk);
        }
        productCdkDao.saveBatch(productCdkList);
        cdkActivityInfo.setIsGenerate(CdkActivityGenerateEnum.GENERATED);
        cdkActivityInfo.updateById();
    }

    @Override
    public Page<CdkExchangeRecordVO> adminCdkExchangeRecord(String userTel, String cdk, Integer pageNo, Integer pageSize, Long cdkActivityId) {
        return productCdkRecordDao.adminCdkExchangeRecord(new Page<>(pageNo, pageSize), userTel, cdk, cdkActivityId);
    }

    @Override
    public void deleteCdkActivity(Long id) {
        CdkActivityInfo cdkActivityInfo = cdkActivityInfoDao.getById(id);
        if (ObjectUtil.isEmpty(cdkActivityInfo)) {
            throw new GlobalRunTimeException(ErrorCode.CDK_ACTIVITY_IS_DOES_NOT_EXIST);
        }

        Integer count = productCdkRecordDao.getCountByCdkActivityId(id);
        if (count > 0) {
            throw new GlobalRunTimeException(ErrorCode.THE_REMAINING_QUANTITY_IS_USED_UP_AND_CANNOT_BE_DELETED);
        }

        if (DateTime.now().isBefore(cdkActivityInfo.getEndTime())) {
            throw new GlobalRunTimeException(ErrorCode.CANNOT_BE_DELETED_WITHIN_THE_VALIDITY_PERIOD);
        }
        cdkActivityInfo.deleteById();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createCustomCDK(CdkActivityInfo cdkActivityInfo, Long id, Integer redemptionTotal) {
        cdkActivityInfo.insert();

        //校验权益道具是否存在 是否下架
        EquityProps equityProps = equityPropsDao.getById(id);
        if (ObjectUtil.isEmpty(equityProps)) {
            throw new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_DO_NOT_EXIST);
        }
        if (!equityProps.getStatus()) {
            throw new GlobalRunTimeException(ErrorCode.EQUITY_PROPS_HAS_BEEN_DESCONTINUED);
        }

        //查询cdk唯一性
        ProductCdk oneByCdk = productCdkDao.getOneByCdk(cdkActivityInfo.getRedemptionCode());
        Assert.isFalse(ObjectUtil.isNotNull(oneByCdk), () -> new GlobalRunTimeException("CDK名称重复"));

        ProductCdk productCdk = new ProductCdk();
        productCdk.setCdk(cdkActivityInfo.getRedemptionCode());
        productCdk.setCdkActivityId(cdkActivityInfo.getId());
        productCdk.setProductId(cdkActivityInfo.getProductId());
        productCdk.setProductType(cdkActivityInfo.getProductType());
        productCdk.setBeginTime(cdkActivityInfo.getBeginTime());
        productCdk.setEndTime(cdkActivityInfo.getEndTime());
        productCdk.insert();
        cdkActivityInfo.setIsGenerate(CdkActivityGenerateEnum.GENERATED);
        cdkActivityInfo.updateById();
    }


    void cdkGrant(Long userId, DigitalCollectionProductInfo digitalCollectionProductInfo, String cdk, Long cdkActivityId) throws GlobalException {
        //减去商品库存  生成CDK的适合都已经扣减过了
//        productStockService.subIntegralStock(digitalCollectionProductInfo.getId(), digitalCollectionProductInfo.getRelationId(), null, 1, userId, CommodityType.INTEGRAL_PRODUCT);
        ProductStockDetail stockDetail = new ProductStockDetail();
        stockDetail.setProductId(digitalCollectionProductInfo.getId());
        stockDetail.setRelationId(digitalCollectionProductInfo.getRelationId());
        stockDetail.setItemId(null);
        stockDetail.setStockChange(-1);
        stockDetail.setUserId(userId);
        stockDetail.setType(CommodityType.INTEGRAL_PRODUCT);
        stockDetail.insert();
        boolean isOpen = false;
        Long boxId = null;
        String boxTitle = null;
        String boxImage = null;
        Long collectionId = null;
        //如果兑换的是盲盒
        switch (digitalCollectionProductInfo.getTypeClassify()) {
            case COLLECTION:
                isOpen = true;
                collectionId = digitalCollectionProductInfo.getRelationId();
                break;
            case BLIND_BOX:
                BoxItem boxItem = boxItemService.openBox(digitalCollectionProductInfo.getId(), digitalCollectionProductInfo.getRelationId());
                collectionId = boxItem.getCollectionId();
                //减去盲盒库存
                productStockService.subIntegralStock(digitalCollectionProductInfo.getId(), digitalCollectionProductInfo.getRelationId(), boxItem.getId(), 1, userId, CommodityType.AIR_DROP);
                BoxProduct boxProduct = boxProductDao.getById(digitalCollectionProductInfo.getRelationId());
                boxId = boxProduct.getId();
                boxTitle = boxProduct.getFirstTitle();
                boxImage = digitalCollectionProductInfo.getCreationContent();
                isOpen = false;
        }
        DigitalCollection digitalCollection = digitalCollectionDao.getById(collectionId);
        UserCollection userCollection = userCollectionService.addCollection(userId, null, digitalCollection.getId(), IdUtil.getSnowflakeNextIdStr(), digitalCollection.getCreationContent(), digitalCollection.getLevel(), digitalCollection.getFirstTitle(),
                digitalCollection.getUserCreatorId(), ReceivedCollectionType.EXCHANGECDK, boxId, boxTitle, boxImage, isOpen, digitalCollectionProductInfo.getId(), 0L, 0L, digitalCollectionProductInfo.getProductNum(), 0, null, null, AddCollectionEnum.STAIR, null, null, false);
        if (digitalCollectionProductInfo.getTypeClassify() == ClassifyType.COLLECTION && digitalCollection.getCollectionType() == DigitalMarketTypeEnum.ECOLOGY) {
            userConsensusService.adjustConsensusService(userId, digitalCollection.getId(), BigDecimal.ONE, UserConsensusTypeEnums.CDK, digitalCollection.getFirstTitle(), null);
        }
        ProductCdkRecord productCdkRecord = new ProductCdkRecord();
        productCdkRecord.setFirstTitle(digitalCollectionProductInfo.getFirstTitle());
        productCdkRecord.setCreationContent(digitalCollectionProductInfo.getCreationContent());
        productCdkRecord.setUserId(userId);
        productCdkRecord.setProductId(digitalCollectionProductInfo.getId());
        productCdkRecord.setCdk(cdk);
        productCdkRecord.setCdkActivityId(cdkActivityId);
        productCdkRecord.setCollectionUuid(userCollection.getCollectionUuid());
        productCdkRecord.setUserCollectionId(userCollection.getId());
        productCdkRecord.insert();

        //插入藏品流转记录
        CollectionCirculatingRecord collectionCirculatingRecord = new CollectionCirculatingRecord();
        collectionCirculatingRecord.setCommodityType(CommodityType.CDK_PRODUCT);
        collectionCirculatingRecord.setTypeClassify(digitalCollectionProductInfo.getTypeClassify());
        collectionCirculatingRecord.setUserId(userId);
        collectionCirculatingRecord.setCollectionId(digitalCollection.getId());
        collectionCirculatingRecord.setReceivedCollectionType(ReceivedCollectionType.EXCHANGECDK);
        collectionCirculatingRecord.insert();
    }
}
